import React, { useState, useEffect } from 'react';
import {
  Typography,
  Card,
  Table,
  Button,
  Space,
  Tag,
  Progress,
  Popconfirm,
  message,
  Row,
  Col,
  Statistic,
  Input,
  Select,
  DatePicker,
  Tooltip,
  Avatar,
  Badge,
  Empty,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  TeamOutlined,
  CalendarOutlined,
  TrophyOutlined,
  UserOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';

// 导入子组件
import CreateActivity from '../ActivityManagement/CreateActivity';
import EditActivity from '../ActivityManagement/EditActivity';
import ActivityDetail from '../ActivityManagement/ActivityDetail';
import ParticipantManagement from '../ActivityManagement/ParticipantManagement';

// 导入API和常量
import {
  getCheckinActivitiesApi,
  deleteCheckinActivityApi,
  getCheckinStatsApi,
} from '../../../api/checkin';
import {
  CHECKIN_STATUS_OPTIONS,
  getStatusColor,
  DEFAULTS,
} from '../CheckType';

const { Title } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

const MyCreatedActivities = () => {
  // 状态管理
  const [mainCheckins, setMainCheckins] = useState([]);
  const [stats, setStats] = useState({});
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    keywords: '',
    status: undefined,
    dateRange: undefined,
  });

  // 模态框状态
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [isParticipantModalVisible, setIsParticipantModalVisible] = useState(false);
  const [selectedActivity, setSelectedActivity] = useState(null);

  // 获取当前用户ID
  const getCurrentUserId = () => 1; // 临时写死，实际应该从登录状态获取

  // 组件挂载时获取数据
  useEffect(() => {
    fetchMyCreatedActivities();
    fetchMyStats();
  }, []);

  // 获取我创建的活动列表
  const fetchMyCreatedActivities = async (params) => {
    try {
      setLoading(true);
      const response = await getCheckinActivitiesApi({
        userId: getCurrentUserId(),
        createdBy: getCurrentUserId(), // 只查询我创建的活动
        ...params,
        pageNum: 1,
        pageSize: DEFAULTS.PAGE_SIZE,
      });
      
      if (response && response.code === '0') {
        setMainCheckins(response.data?.list || []);
      } else {
        message.error(response.msg || '获取活动列表失败');
      }
    } catch (error) {
      console.error('获取活动列表失败:', error);
      message.error('获取活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取我的统计数据
  const fetchMyStats = async () => {
    try {
      const response = await getCheckinStatsApi({
        userId: getCurrentUserId(),
        createdBy: getCurrentUserId(), // 只统计我创建的活动
      });
      
      if (response && response.code === '0') {
        setStats(response.data || {});
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    }
  };

  // 处理搜索
  const handleSearch = () => {
    // 构建搜索参数，将时间区间拆分为开始和结束时间
    const params = {
      ...searchParams,
      startDate: searchParams.dateRange?.[0]?.format('YYYY-MM-DD'),
      endDate: searchParams.dateRange?.[1]?.format('YYYY-MM-DD'),
    };
    
    // 移除dateRange字段，避免传递给后端
    delete params.dateRange;
    
    fetchMyCreatedActivities(params);
  };

  // 处理重置搜索
  const handleResetSearch = () => {
    setSearchParams({
      keywords: '',
      type: undefined,
      status: undefined,
      dateRange: undefined,
    });
    setTimeout(() => {
      fetchMyCreatedActivities();
    }, 100);
  };

  // 处理创建活动
  const handleCreateActivity = () => {
    setIsCreateModalVisible(true);
  };

  // 处理编辑活动
  const handleEditActivity = (activity) => {
    setSelectedActivity(activity);
    setIsEditModalVisible(true);
  };

  // 处理查看详情
  const handleViewDetail = (activity) => {
    setSelectedActivity(activity);
    setIsDetailModalVisible(true);
  };

  // 处理管理参与者
  const handleManageParticipants = (activity) => {
    setSelectedActivity(activity);
    setIsParticipantModalVisible(true);
  };

  // 处理删除活动
  const handleDeleteActivity = async (id) => {
    try {
      const response = await deleteCheckinActivityApi({
        id,
        userId: getCurrentUserId()
      });
      
      if (response && response.code === '0') {
        message.success('删除成功');
        fetchMyCreatedActivities();
        fetchMyStats();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 处理操作成功回调
  const handleOperationSuccess = () => {
    fetchMyCreatedActivities();
    fetchMyStats();
  };

  const getStatusLabel = (status) => {
    const statusConfig = CHECKIN_STATUS_OPTIONS.find(s => s.value === status);
    return statusConfig?.label || '未知状态';
  };

  // 表格列定义
  const columns = [
    {
      title: '活动信息',
      key: 'activity',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', fontSize: 16, marginBottom: 4 }}>
            {record.title}
            {record.createdBy === getCurrentUserId() && (
              <Tag color="gold" style={{ marginLeft: 8, fontSize: 10 }}>
                我创建的
              </Tag>
            )}
          </div>
          <div style={{ fontSize: 12, color: '#666', marginBottom: 8 }}>
            {record.description}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> 
            <Tag color={getStatusColor(record.status)}>
              {getStatusLabel(record.status)}
            </Tag>
            {record.tags && record.tags.map((tag, index) => (
              <Tag key={index} color="default">{tag}</Tag>
            ))}
          </div>
        </div>
      ),
    },
    {
      title: '时间信息',
      key: 'timeInfo',
      width: 200,
      render: (_, record) => (
        <div style={{ fontSize: 12, lineHeight: 1.6 }}>
          <div><strong>开始:</strong> {dayjs(record.startDate).format('MM-DD')}</div>
          <div><strong>结束:</strong> {dayjs(record.endDate).format('MM-DD')}</div>
          <div><strong>创建:</strong> {dayjs(record.createdAt).format('MM-DD')}</div>
        </div>
      ),
    },
    {
      title: '进度统计',
      key: 'progress',
      width: 200,
      render: (_, record) => (
        <div>
          <div style={{ marginBottom: 8 }}>
            <Progress
              percent={record.overallProgress || 0}
              size="small"
              status={record.overallProgress >= 100 ? 'success' : 'active'}
            />
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>
            完成天数: {record.completedDays || 0}/{record.targetDays || 0}
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>
            参与者: {record.totalParticipants || 0} 人
          </div>
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <Space size="small">
            <Tooltip title="查看详情">
              <Button
                type="link"
                icon={<EyeOutlined />}
                onClick={() => handleViewDetail(record)}
              >
                详情
              </Button>
            </Tooltip>
            <Tooltip title="编辑活动">
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={() => handleEditActivity(record)}
              >
                编辑
              </Button>
            </Tooltip>
          </Space>
          <Space size="small">
            <Tooltip title="管理参与者">
              <Button
                type="link"
                icon={<TeamOutlined />}
                onClick={() => handleManageParticipants(record)}
              >
                参与者
              </Button>
            </Tooltip>
          </Space>
          <Space size="small">
            <Tooltip title="删除活动">
              <Popconfirm
                title="确定要删除这个活动吗？"
                onConfirm={() => handleDeleteActivity(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="link"
                  danger
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </Popconfirm>
            </Tooltip>
          </Space>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面头部 */}
      <Title level={2} style={{ marginBottom: '24px' }}>
        我创建的活动
      </Title>
      <Title level={4} type="secondary" style={{ marginBottom: '32px' }}>
        管理您创建的所有打卡活动，包括编辑、删除和查看详情
      </Title>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="我创建的活动"
              value={stats.totalActivities || 0}
              suffix="个"
              prefix={<UserOutlined style={{ color: '#1890ff' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="进行中"
              value={stats.activeActivities || 0}
              suffix="个"
              prefix={<CalendarOutlined style={{ color: '#52c41a' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成"
              value={stats.completedActivities || 0}
              suffix="个"
              prefix={<TrophyOutlined style={{ color: '#faad14' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总参与人数"
              value={stats.totalParticipants || 0}
              suffix="人"
              prefix={<TeamOutlined style={{ color: '#722ed1' }} />}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和筛选 */}
      <Card style={{ marginBottom: 24 }}>
        <Row gutter={16} align="middle">
          <Col span={6}>
            <Search
              placeholder="搜索活动名称或描述"
              value={searchParams.keywords}
              onChange={(e) => setSearchParams(prev => ({ ...prev, keywords: e.target.value }))}
              onSearch={handleSearch}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="活动状态"
              value={searchParams.status}
              onChange={(value) => setSearchParams(prev => ({ ...prev, status: value }))}
              allowClear
              style={{ width: '100%' }}
            >
              {CHECKIN_STATUS_OPTIONS.map(status => (
                <Option key={status.value} value={status.value}>
                  {status.label}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              value={searchParams.dateRange}
              onChange={(dates) => setSearchParams(prev => ({ ...prev, dateRange: dates }))}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Space>
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleResetSearch}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 活动列表 */}
      <Card 
        title="我的活动列表" 
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setIsCreateModalVisible(true)}
          >
            创建活动
          </Button>
        }
      >
        {mainCheckins.length > 0 ? (
          <Table
            columns={columns}
            dataSource={mainCheckins}
            loading={loading}
            rowKey="id"
            pagination={{
              total: mainCheckins.length,
              pageSize: DEFAULTS.PAGE_SIZE,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            }}
          />
        ) : (
          <Empty
            description="您还没有创建任何打卡活动"
            style={{ padding: '60px 0' }}
          />
        )}
      </Card>

      {/* 模态框组件 */}
      <CreateActivity
        visible={isCreateModalVisible}
        onCancel={() => setIsCreateModalVisible(false)}
        onSuccess={handleOperationSuccess}
      />

      <EditActivity
        visible={isEditModalVisible}
        activity={selectedActivity}
        onCancel={() => {
          setIsEditModalVisible(false);
          setSelectedActivity(null);
        }}
        onSuccess={handleOperationSuccess}
      />

      <ActivityDetail
        visible={isDetailModalVisible}
        activity={selectedActivity}
        onCancel={() => {
          setIsDetailModalVisible(false);
          setSelectedActivity(null);
        }}
      />

      <ParticipantManagement
        visible={isParticipantModalVisible}
        activityId={selectedActivity?.id}
        onCancel={() => {
          setIsParticipantModalVisible(false);
          setSelectedActivity(null);
        }}
        onSuccess={handleOperationSuccess}
      />
    </div>
  );
};

export default MyCreatedActivities; 